﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using elfam.web.Models;
using elfam.web.Paging.Prototype;

namespace elfam.web.Paging.Product
{
    public class ProductListQueryBuilder: QueryBuilder<Models.Product>
    {
        private Category _category;


        public ProductListQueryBuilder(ProductListSearchCriteria criteria)
            : base(criteria)
        {
            if (criteria.CategoryId.HasValue)
                _category = DaoTemplate.FindByID<Category>(criteria.CategoryId);
        }

        protected override Dictionary<string, string> initAliases()
        {
            return new Dictionary<string, string>()
                       {
                           {"name", "p.Name"},
                           {"price", "p.Price"},
                           {"date", "p.Date"},
                           {"category", "p.Category.Name"}
                       };
        }

        protected override string getTotalCountHql()
        {
            if (_category != null)
            return string.Format("select count(p.Id) from Product p where p.Category.Id in ({0})", 
                string.Join(",", _category.ThisAndSubcategories().Select(x => x.Id.ToString()).ToArray()));
            return "select count(p.Id) from Product p";
        }

        protected override string getHql()
        {
            if (_category != null)
            {
                return @"select p
                from Product p join p.Incomes inc
                where p.Category.Id in (" + string.Join(",", _category.ThisAndSubcategories().Select(x => x.Id.ToString()).ToArray()) + @")
                group by p.Id, p.Name, p.Description, p.ShortDescription, p.Price, p.Date, p.Category, p.Category.Name, p.SKU, p.Size, p.Weight, p.Color, p.Country  
                 order by case when sum(inc.QuantityCurrent) > 0 then 0 else 1 end";
            }
            return @"select p 
                from Product p join p.Incomes inc
                group by p.Id, p.Name, p.Description, p.ShortDescription, p.Price, p.Date, p.Category, p.Category.Name,p.SKU, p.Size, p.Weight, p.Color, p.Country  
                 order by case when sum(inc.QuantityCurrent) > 0 then 0 else 1 end";
        }

        protected override string applyOrder(string hql)
        {
            if (string.IsNullOrEmpty(_searchCriteria.SortExpression))
                return hql;
            Dictionary<string, string> aliases = initAliases();
            if (!aliases.ContainsKey(_searchCriteria.SortExpression))
                return hql;

            string direction = string.IsNullOrEmpty(_searchCriteria.SortDirection) ? SearchCriteria.AscSearchOrder : _searchCriteria.SortDirection;
            string order = string.Format(" ,{0} {1} ", aliases[_searchCriteria.SortExpression], direction);
            return hql + order;
        }
    }
}
